package com.boboPlanet.user.filter;

import com.alibaba.fastjson.JSON;
import com.boboPlanet.comm.constance.CommInstance;
import com.boboPlanet.comm.context.LoginUserContext;
import com.boboPlanet.comm.entity.po.LoginUserInfoPO;
import com.boboPlanet.comm.result.ResponseResult;
import com.boboPlanet.user.annotation.LimitPass;
import com.boboPlanet.user.enums.ConstanceEnum;
import com.boboPlanet.user.mapper.UserOperationMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;

/**
 * @Description: TODO 星球拦截器 执行顺序 preHandle – Controller 方法 – postHandle – afterCompletion
 * @Author: mis_wu
 * @Date: 2023/3/8
 * todo: 在webmvc配置类中添加
 **/
@Component
@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class PlanetMiddleRequestInterceptor implements HandlerInterceptor {

    @Autowired
    private UserOperationMapper userOperationMapper;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String url = request.getRequestURI();

        //放行swagger
//        log.error("swagger uri: {}",url);
        if (ConstanceEnum.swagger_url.contains(url)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //放行 LimitPass 注解
        LimitPass limitPass = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), LimitPass.class);
        if (limitPass != null && limitPass.value()){
            return true;
        }
        //没生效
        boolean allow = ((HandlerMethod) handler).getMethod().isAnnotationPresent(LimitPass.class);
        if (allow){
            return true;
        }
        String token = request.getHeader(CommInstance.TOKEN_AUTHORIZATION);
        LoginUserInfoPO userInfo = userOperationMapper.queryLoginUserInfoByToken(token);
        if(ObjectUtils.isEmpty(userInfo)){
            ResponseResult<String> result = ResponseResult.error("用户登录信息异常,请重新登录...");
            //下载文件流时outputStream.write(bytes);在这要重置response
            response.reset();
            response.setStatus(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value());
            response.setContentType(CommInstance.RESPONSE_CONTENT_TYPE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            PrintWriter resp = response.getWriter();
            resp.write(JSON.toJSONString(result));
            return false;
        }
        LoginUserContext.mock(userInfo);
        return true;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
